package cn.edu.hqu.cst.lingshou03.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.edu.hqu.cst.lingshou03.mapper.OrderMapper;
import cn.edu.hqu.cst.lingshou03.mapper.ProductMapper;
import cn.edu.hqu.cst.lingshou03.model.Order;
import cn.edu.hqu.cst.lingshou03.model.Product;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class OrderService {

    private final OrderMapper orderMapper;
    private final ProductMapper productMapper;
    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    public OrderService(OrderMapper orderMapper, ProductMapper productMapper) {
        this.orderMapper = orderMapper;
        this.productMapper = productMapper;
    }

    @Transactional
    public String createOrder(Order order) {
        // 检查产品库存，如果库存足够，则创建订单
        Product product = productMapper.selectById(order.getProductId());
        if (product != null && product.getStock() >= order.getQuantity()) {
            product.setStock(product.getStock() - order.getQuantity()); // 减少库存
            productMapper.updateById(product); // 更新产品信息
            orderMapper.insert(order); // 创建订单
        } else {
            // 处理库存不足的情况，如抛出异常
            throw new RuntimeException("Insufficient stock for product: " + order.getProductId());
        }
        return null;
    }

    @Transactional
    public void updateOrderStatus(Long orderId, String newStatus) {
        Order order = orderMapper.selectById(orderId);
        if (order != null) {
            order.setStatus(newStatus);
            orderMapper.updateById(order);
        } else {
            // 处理订单不存在的情况，如抛出异常
            throw new RuntimeException("Order not found: " + orderId);
        }
    }

    public List<Order> getAllOrders() {
        try {
            // 从数据库获取所有订单
            List<Order> allOrders = orderMapper.selectAll();  // 假设这是获取所有订单的方法
            if (allOrders == null) {
                return Collections.emptyList();  // 返回空列表而不是 null
            }
            return allOrders;
        } catch (Exception e) {
            // 处理可能的异常，例如数据库连接问题
            log.error("Failed to get all orders: ", e);
            return Collections.emptyList();  // 在异常情况下也返回空列表
        }
    }

    public Order saveOrder(Order newOrder) {
        return null;
    }
}